#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

#define MAXLINE 1024

void err_quit(const char* fmt,...){
	va_list ap;
	
	va_start(ap,fmt);
	fprintf(stderr,fmt,ap);
	va_end(ap);
	exit(1);
}

void err_sys(const char* fmt,...){
	va_list ap;
	
	va_start(ap,fmt);
	fprintf(stderr,fmt,ap);
	va_end(ap);
	exit(1);
}

int main(int argc,char** argv){
	int sockfd,n;
	char recvline[MAXLINE+1];
	struct sockaddr_in servaddr;
	
	if(argc!=2){
		fprintf(stderr,"usage:daytime <IPADDRESS> %d:%s\n",errno,strerror(errno));
		exit(1);
	}
	
	if( (sockfd=socket(AF_INET,SOCK_STREAM,0))<0 ){
		fprintf(stderr,"socket invoke error\n");
		exit(1);
	}
	
	//memset(&servaddr,0,sizeof(servaddr));
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_port=htons(13);
	if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr) <=0){
		fprintf(stderr,"pton error %s\n",argv[1]);
		exit(1);
	}
	
	if(connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr))<0){
		fprintf(stderr,"connect error");
	}
	
	while( (n=read(sockfd,recvline,MAXLINE))>0 ){
		recvline[n]=0;
		fputs(recvline,stdout);
	}
	if(n<0)
		fprintf(stderr,"read error\n");
	exit(0);
}
